<template>
  <div class="leader-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>团长管理</span>
        </div>
      </template>
      <!-- 搜索栏 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入内容" @input="handleMultiInput" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入内容" @input="handleMultiInput" />
          </el-form-item>
          <el-form-item label="自提点名称">
            <el-input v-model="searchForm.storeName" placeholder="请输入内容" @input="handleMultiInput" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="searchForm.address" placeholder="请输入内容" @input="handleMultiInput" />
          </el-form-item>
          <el-form-item label="自提点类型">
            <el-select v-model="searchForm.storeType" style="width: 120px" placeholder="全部" filterable @change="handleMultiInput">
              <el-option v-for="item in storeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="团长标签">
            <el-select v-model="searchForm.leaderTag" style="width: 120px" placeholder="全部" @change="handleMultiInput">
              <el-option v-for="item in leaderTagOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">检索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleAddTag">添加标签</el-button>
          <el-button type="success" @click="handleValid">有效</el-button>
          <el-button type="danger" @click="handleInvalid">无效</el-button>
          <el-button @click="handleExport">导出</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="团长ID" width="140" />
        <el-table-column prop="auditTime" label="审核时间" width="160" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="storeName" label="自提点名称" width="150" />
        <el-table-column prop="address" label="自提点地址" min-width="180" />
        <el-table-column prop="storeType" label="自提点类型" width="100" />
        <el-table-column prop="dealAmount" label="成交金额" width="110" />
        <el-table-column prop="dealOrder" label="成交订单" width="100" />
        <el-table-column prop="dealUser" label="成交订单" width="100" />
        <el-table-column prop="status" label="状态" width="80" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="danger" link @click="handleInvalidRow(scope.row)">无效</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页和统计 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10]"
          layout="prev, pager, next, ->, sizes"
          :total="total"
          :pager-count="5"
          background
          prev-text="«"
          next-text="»"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :popper-class="'custom-pagination-sizes'"
        />
        <div class="pagination-info">
          当前条件共检索到 <span style="color:#f00">{{ total }}</span> 条相关信息
        </div>
      </div>
    </el-card>
  </div>
  <!-- 在表格下方添加模态框 -->
  <el-dialog v-model="dialogVisible" title="团长信息" width="1100px" :close-on-click-modal="false">
    <div v-if="currentRow">
      <!-- 团长信息 -->
      <h4>团长信息</h4>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="团长ID">{{ currentRow.id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核通过时间">{{ currentRow.auditTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentRow.status || '-' }}</el-descriptions-item>
        <el-descriptions-item label="授权微信信息">{{ currentRow.wxInfo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="团长姓名">{{ currentRow.name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentRow.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备用电话">{{ currentRow.backupPhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="自提点名称">{{ currentRow.storeName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="自提点类型">{{ currentRow.storeType || '-' }}</el-descriptions-item>
        <el-descriptions-item label="自提点地址">{{ currentRow.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="位置坐标">{{ currentRow.coordinate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="门牌号">{{ currentRow.doorNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="开始营业时间">{{ currentRow.openTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="结束营业时间">{{ currentRow.closeTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="邀请码">{{ currentRow.inviteCode || '-' }}</el-descriptions-item>
      </el-descriptions>
      <div style="margin: 16px 0;">
        客户标签：
        <el-tag type="danger" effect="plain" style="margin-right:8px;">高端团长</el-tag>
        <el-tag type="info" effect="plain" style="margin-right:8px;">品质团长</el-tag>
        <el-tag type="info" effect="plain">客单量高</el-tag>
      </div>
      <!-- 审核资料 -->
      <h4>团长审核资料</h4>
      <el-row gutter="24">
        <el-col :span="6">
          <el-image v-if="currentRow.licenseImg" :src="currentRow.licenseImg" style="width:160px;height:160px;" fit="contain" />
          <div v-else style="width:160px;height:160px;background:#fafbfc;border:1px solid #eee;"></div>
          <div style="text-align:center;margin-top:8px;">营业执照</div>
        </el-col>
        <el-col :span="6">
          <el-image v-if="currentRow.storeImg" :src="currentRow.storeImg" style="width:160px;height:160px;" fit="contain" />
          <div v-else style="width:160px;height:160px;background:#fafbfc;border:1px solid #eee;"></div>
          <div style="text-align:center;margin-top:8px;">自提点照片</div>
        </el-col>
        <el-col :span="6">
          <el-image v-if="currentRow.idCardFront" :src="currentRow.idCardFront" style="width:160px;height:160px;" fit="contain" />
          <div v-else style="width:160px;height:160px;background:#fafbfc;border:1px solid #eee;"></div>
          <div style="text-align:center;margin-top:8px;">身份证正面</div>
        </el-col>
        <el-col :span="6">
          <el-image v-if="currentRow.idCardBack" :src="currentRow.idCardBack" style="width:160px;height:160px;" fit="contain" />
          <div v-else style="width:160px;height:160px;background:#fafbfc;border:1px solid #eee;"></div>
          <div style="text-align:center;margin-top:8px;">身份证反面</div>
        </el-col>
      </el-row>
      <!-- 团长账户 -->
      <h4 style="margin-top:32px;">团长账户</h4>
      <el-row gutter="24" style="margin-bottom: 16px;">
        <el-col :span="4">账户余额：100.00元</el-col>
        <el-col :span="4">已提现金额：100.00元</el-col>
        <el-col :span="4">待到账佣金：100.00元</el-col>
        <el-col :span="4">已到账佣金：1000.00元</el-col>
        <el-col :span="4">成交金额：20000.00元</el-col>
        <el-col :span="4">成交订单：10000笔</el-col>
      </el-row>
      <!-- 佣金记录 -->
      <h4>佣金记录</h4>
      <el-form :inline="true" style="margin-bottom: 12px;">
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="commissionDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleCommissionDateChange"
            style="width: 260px;"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="commissionFilter.status" style="width:120px;" @change="handleCommissionDateChange">
            <el-option label="全部" value="" />
            <el-option label="已到账" value="已到账" />
            <el-option label="待到账" value="待到账" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="commissionTableData" style="width:100%;margin-bottom:12px;">
        <el-table-column prop="orderTime" label="商品下单时间" width="180" />
        <el-table-column prop="estimateAmount" label="预计佣金金额" width="120" />
        <el-table-column prop="actualAmount" label="实际到账佣金" width="120" />
        <el-table-column prop="orderId" label="对应订单号" width="200" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column prop="arriveTime" label="到账时间" width="180" />
      </el-table>
      <el-pagination
        v-model:current-page="commissionPage"
        v-model:page-size="commissionPageSize"
        :total="commissionTotal"
        :page-sizes="[2, 5, 10]"
        layout="prev, pager, next, ->, sizes"
        background
        style="margin-top:8px;"
        @current-change="handleCommissionPageChange"
        @size-change="handleCommissionSizeChange"
      />
    </div>
  </el-dialog>
  <el-dialog v-model="addTagDialogVisible" title="添加标签" width="500px" :close-on-click-modal="false">
    <div style="margin-bottom:24px;display:flex;gap:24px;">
      <el-button
        v-for="item in tagOptions"
        :key="item"
        :type="selectedTags.includes(item) ? 'primary' : 'default'"
        @click="toggleTag(item)"
        plain
        style="min-width:120px"
      >
        {{ item }}
      </el-button>
    </div>
    <div style="text-align:right;">
      <el-button @click="addTagDialogVisible=false">取消</el-button>
      <el-button type="danger" @click="confirmAddTag">确定</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="invalidDialogVisible" title="设置无效" width="500px" :close-on-click-modal="false">
    <div style="margin-bottom:16px;display:flex;gap:12px;">
      <el-button
        v-for="item in invalidReasonOptions"
        :key="item"
        :type="selectedInvalidReason === item ? 'danger' : 'default'"
        @click="selectInvalidReason(item)"
        plain
      >
        {{ item }}
      </el-button>
    </div>
    <el-input
      v-model="inputInvalidReason"
      placeholder="请手动输入原因"
      maxlength="50"
      show-word-limit
      style="margin-bottom:24px;"
    />
    <div style="text-align:right;">
      <el-button @click="invalidDialogVisible=false">取消</el-button>
      <el-button type="danger" @click="confirmInvalid">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const addTagDialogVisible = ref(false)
const tagOptions = ["高端团战", "品质团长", "客单量高"]
const selectedTags = ref<string[]>([])

const invalidDialogVisible = ref(false)
const invalidTargetRow = ref<LeaderRow | null>(null)
const invalidReasonOptions = ['团长违规', '信息填写错误', '恶意注册']
const selectedInvalidReason = ref('')
const inputInvalidReason = ref('')

// searchForm初始值
const searchForm = ref({
  name: '',
  phone: '',
  storeName: '',
  address: '',
  storeType: '', // 默认全部
  leaderTag: ''  // 默认全部
})
const storeTypeOptions = [
  { label: '全部', value: '' },
  { label: '便利店', value: '便利店' },
  { label: '快递点', value: '快递点' }
]
const leaderTagOptions = [
  { label: '全部', value: '' },
  { label: '金牌', value: '金牌' },
  { label: '银牌', value: '银牌' }
]

interface LeaderRow {
  id: string
  auditTime: string
  name: string
  phone: string
  storeName: string
  address: string
  storeType: string
  dealAmount: string
  dealOrder: number
  dealUser: number
  status: string
  leaderTag: string
}

const allData: LeaderRow[] = [
  ...[...Array(10)].map((_, i) => ({
    id: `20200220000${i+1}`,
    auditTime: '2020-02-14 14:30:30',
    name: '张三',
    phone: `${130 + i}55555555`,
    storeName: '菜鸟驿站',
    address: '北京市石景山区',
    storeType: '便利店',
    dealAmount: '1000.00元',
    dealOrder: 2000,
    dealUser: 2000,
    status: i % 2 === 0 ? '有效' : '无效',
    leaderTag: i % 2 === 0 ? '金牌' : '银牌'
  }))
]

const tableData = ref<LeaderRow[]>([])
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref(allData.length)
const loading = ref(false)
const selectedRows = ref<LeaderRow[]>([])
const dialogVisible = ref(false)
const currentRow = ref<any>(null)

function handleView(row: any) {
  currentRow.value = row
  dialogVisible.value = true
}

const updateTableData = () => {
  // 可加筛选逻辑
  let filtered = [...allData]
  // ...筛选条件略
  total.value = filtered.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  // 保证dealOrder和dealUser为number类型
  tableData.value = filtered.slice(start, end).map(item => ({
    ...item,
    dealOrder: typeof item.dealOrder === 'number' ? item.dealOrder : Number(item.dealOrder),
    dealUser: typeof item.dealUser === 'number' ? item.dealUser : Number(item.dealUser)
  }))
}
const handleSearch = () => {
  currentPage.value = 1
  updateTableData()
}
const handleReset = () => {
  searchForm.value = {
    name: '', phone: '', storeName: '', address: '', storeType: '', leaderTag: ''
  }
  currentPage.value = 1
  updateTableData()
}
const handleSelectionChange = (rows: LeaderRow[]) => {
  selectedRows.value = rows
}
const handleAddTag = () => {
  addTagDialogVisible.value = true
}
const toggleTag = (tag: string) => {
  const idx = selectedTags.value.indexOf(tag)
  if (idx > -1) {
    selectedTags.value.splice(idx, 1)
  } else {
    selectedTags.value.push(tag)
  }
}
const confirmAddTag = () => {
  addTagDialogVisible.value = false
  // 这里可以将选中的标签传递到后端或页面其它地方
  console.log('选中的标签:', selectedTags.value)
}
const handleValid = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要设置为有效的数据')
    return
  }
  selectedRows.value.forEach(row => {
    row.status = '有效'
    // 同步到allData
    const idx = allData.findIndex(item => item.id === row.id)
    if (idx > -1) allData[idx].status = '有效'
  })
  updateTableData()
  ElMessage.success('设置有效')
}
const handleInvalid = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要设置为无效的数据')
    return
  }
  invalidTargetRow.value = selectedRows.value[0]
  selectedInvalidReason.value = invalidReasonOptions[0]
  inputInvalidReason.value = ''
  invalidDialogVisible.value = true
}
const selectInvalidReason = (reason: string) => {
  selectedInvalidReason.value = reason
}
const confirmInvalid = () => {
  if (invalidTargetRow.value) {
    invalidTargetRow.value.status = '无效'
    // 记录原因（可加字段invalidReason到数据结构，或仅console.log）
    const reason = inputInvalidReason.value || selectedInvalidReason.value
    // 同步到allData
    const idx = allData.findIndex(item => item.id === invalidTargetRow.value?.id)
    if (idx > -1) allData[idx].status = '无效'
    updateTableData()
    ElMessage.success('设置无效，原因：' + reason)
    // 你可以在这里将reason保存到后端或本地
  }
  invalidDialogVisible.value = false
}
const handleExport = () => {
  ElMessage.info('导出数据')
}
const handleInvalidRow = (row: LeaderRow) => {
  invalidTargetRow.value = row
  selectedInvalidReason.value = invalidReasonOptions[0]
  inputInvalidReason.value = ''
  invalidDialogVisible.value = true
}
const handleSizeChange = (val: number | string) => {
  pageSize.value = typeof val === 'number' ? val : Number(val)
  currentPage.value = 1
  updateTableData()
}
const handleCurrentChange = (val: number | string) => {
  currentPage.value = typeof val === 'number' ? val : Number(val)
  updateTableData()
}
function getRandomInt(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomStatus() {
  return Math.random() > 0.5 ? '有效' : '无效';
}
function getRandomDate() {
  const now = new Date();
  return now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0') + ' ' + String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0') + ':' + String(now.getSeconds()).padStart(2, '0');
}
function loadLeaderManagementList() {
  const list = JSON.parse(localStorage.getItem('leaderManagementList') || '[]');
  // 为新数据补充随机字段
  const filled = list.map((item: any) => ({
    ...item,
    auditTime: item.auditTime || getRandomDate(),
    dealAmount: item.dealAmount || getRandomInt(1000, 9999) + '.00元',
    dealOrder: typeof item.dealOrder === 'number' ? item.dealOrder : getRandomInt(100, 999),
    dealUser: typeof item.dealUser === 'number' ? item.dealUser : getRandomInt(100, 999),
    status: item.status || getRandomStatus()
  }));
  allData.splice(0, allData.length, ...filled); // 替换为已通过数据
  updateTableData();
}
onMounted(() => {
  loadLeaderManagementList();
});
updateTableData()

const commissionFilter = ref({ status: '' })
const commissionPage = ref<number>(1)
const commissionPageSize = ref<number>(10)
const commissionTotal = ref(3)
const commissionAllData = Array.from({ length: 10 }).map((_, i) => {
  const hour = 12 + i;
  const minute = Math.floor(Math.random() * 60); // 0~59
  return {
    orderTime: `2021-01-31 ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:20`,
    estimateAmount: '50元',
    actualAmount: '50元',
    orderId: `10180932997631000${i}`,
    status: i % 2 === 0 ? '已到账' : '待到账',
    arriveTime: '2020-02-24 14:12:30'
  }
})
const commissionTableData = ref<any[]>([])
const commissionDateRange = ref<[string, string] | []>([])

const handleCommissionDateChange = () => {
  let filtered = commissionAllData
  if (commissionDateRange.value && commissionDateRange.value.length === 2) {
    const [start, end] = commissionDateRange.value
    filtered = filtered.filter(item => {
      // 假设orderTime格式为 '2021-01-31 12:93:20'
      return dayjs(item.orderTime) >= dayjs(start) && dayjs(item.orderTime) <= dayjs(end)
    })
  }
  if (commissionFilter.value.status) {
    filtered = filtered.filter(item => item.status === commissionFilter.value.status)
  }
  commissionTotal.value = filtered.length
  commissionTableData.value = filtered.slice((commissionPage.value-1)*commissionPageSize.value, commissionPage.value*commissionPageSize.value)
}
function updateCommissionTable() {
  let filtered = commissionAllData
  if (commissionFilter.value.status) {
    filtered = filtered.filter(item => item.status === commissionFilter.value.status)
  }
  commissionTotal.value = filtered.length
  commissionTableData.value = filtered.slice((commissionPage.value-1)*commissionPageSize.value, commissionPage.value*commissionPageSize.value)
}
watch([commissionFilter, commissionPage, commissionDateRange], handleCommissionDateChange, { immediate: true })
function handleCommissionPageChange(val: number | string) {
  commissionPage.value = typeof val === 'number' ? val : Number(val)
}
function handleCommissionSizeChange(val: number | string) {
  commissionPageSize.value = typeof val === 'number' ? val : Number(val)
  commissionPage.value = 1
  updateCommissionTable()
}

const handleMultiInput = () => {
  let filtered = allData.filter(item => {
    const nameMatch = !searchForm.value.name || item.name.includes(searchForm.value.name)
    const phoneMatch = !searchForm.value.phone || item.phone.includes(searchForm.value.phone)
    const addressMatch = !searchForm.value.address || item.address.includes(searchForm.value.address)
    const storeNameMatch = !searchForm.value.storeName || item.storeName.includes(searchForm.value.storeName)
    const storeTypeMatch = !searchForm.value.storeType || searchForm.value.storeType === '' || item.storeType === searchForm.value.storeType
    const leaderTagMatch = !searchForm.value.leaderTag || searchForm.value.leaderTag === '' || item.leaderTag === searchForm.value.leaderTag
    return nameMatch && phoneMatch && addressMatch && storeNameMatch && storeTypeMatch && leaderTagMatch
  })
  total.value = filtered.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = filtered.slice(start, end).map(item => ({
    ...item,
    dealOrder: typeof item.dealOrder === 'number' ? item.dealOrder : Number(item.dealOrder),
    dealUser: typeof item.dealUser === 'number' ? item.dealUser : Number(item.dealUser)
  }))
}
</script>

<style scoped>
.leader-management {
  padding: 20px;
}
.box-card {
  width: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-area {
  margin-bottom: 20px;
}
.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pagination-info {
  color: #999;
  font-size: 16px;
  margin-left: 16px;
}
::v-deep .el-pagination__sizes .el-input__inner {
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  background: #fff;
  font-size: 16px;
  color: #606266;
  padding: 0 10px;
  height: 32px;
  min-width: 90px;
  text-align: center;
}
::v-deep .el-pagination__sizes .el-input__suffix {
  right: 8px;
}
::v-deep .el-pagination__sizes .el-input__inner::placeholder {
  color: #bfbfbf;
}
</style> 